package com.lujieni.springbooteasyexcel.filters;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.TimeZone;

/**
 * @Author：小鹿爱吃鱼
 * @Date: 2025/5/1 18:28
 * @Description:
 */
@Component
public class TimezoneFilter extends OncePerRequestFilter {

    private static final HashMap<String, String> timezoneMap = new HashMap<>();

    public static final ThreadLocal<SimpleDateFormat> dateFormatContext = new ThreadLocal<SimpleDateFormat>();

    static {
        timezoneMap.put("zh", "Asia/Shanghai");
        timezoneMap.put("en", "America/New_York");
        timezoneMap.put("jp", "Asia/Tokyo");
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String lanuage = request.getHeader("lanuage");
        if(StringUtils.isEmpty(lanuage)){
            dateFormatContext.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        }else{
            String timezone = timezoneMap.get(lanuage);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timezone));
            dateFormatContext.set(simpleDateFormat);
        }
        try{
            filterChain.doFilter(request, response);
        }finally {
            dateFormatContext.remove();
        }

    }
}
